package com.lxl.miaosha.service;

import com.lxl.miaosha.entity.Product;
import com.lxl.miaosha.entity.ProductRecord;
import com.lxl.miaosha.mapper.ProductMapper;
import com.lxl.miaosha.mapper.ProductRecordMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RabbitListener(queues = "MiaoshaQueue")//监听的队列名称 MyDirectQueue
public class DirectReceiver {

    private static final Logger LOGGER = LoggerFactory.getLogger(DirectReceiver.class);


    @Autowired
    ProductMapper productMapper;

    @Autowired
    ProductRecordMapper productRecordMapper;



    @RabbitHandler(isDefault = true)
    public void process(Map ReceiveMessage) {
        System.out.println("消费者DirectReceiver收到消息:" + ReceiveMessage.get("messageData"));
        Integer userId= Integer.valueOf(ReceiveMessage.get("messageData").toString());//获取消息中的关键数据，即用户编号
        Product product = productMapper.findByProductNo("110");//获得产品信息
        if (product != null && product.getTotal() > 0) { //判断库存
            //更新库存表，库存量减少1。返回1说明更新成功。返回0说明库存已经为0
            product.setTotal(product.getTotal()-1);
            int i = productMapper.updateById(product);
            if(i>0){
                //插入记录
                productRecordMapper.insert(new ProductRecord("110", userId));
                //发送短信
                LOGGER.info("用户{}抢单成功", userId);
            }else {
                LOGGER.error("用户{}抢单失败", userId);
            }
        } else {
            LOGGER.error("用户{}抢单失败", userId);
        }
    }
}

